package org.kazuhiko.rpg.client.net.packet;

import java.util.HashMap;
import java.util.Map;

public final class PacketBuilder
{
	private PacketDefinition definition;
	
	private Map<String, Object> values = new HashMap<String, Object>();
	
	public PacketBuilder( PacketDefinition definition )
	{
		this.definition = definition;
	}
	
	public Packet toPacket()
	{
		return new Packet( definition, values );
	}
	
	private void validateField( String name, DataType type )
	{
		for( PacketField field : definition.getFields() )
		{
			if( field.getName().equals( name ) )
			{
				if( field.getType().equals( type ) )
				{
					return;
				}
				else
				{
					throw new IllegalArgumentException( "Incorrect data type - expecting " + field.getType() + " but " + type + " given..." );
				}
			}
		}
		
		throw new IllegalArgumentException( "No field name " + name + "." );
	}
	
	public PacketBuilder putByte( String name, int value )
	{
		validateField( name, DataType.BYTE );
		
		values.put( name, ( byte ) value );
		
		return this;
	}
	
	public PacketBuilder putShort( String name, int value )
	{
		validateField( name, DataType.SHORT );
		
		values.put( name,  ( short ) value );
		
		return this;
	}
	
	public PacketBuilder putInt( String name, int value )
	{
		validateField( name, DataType.INT );
		
		values.put( name,  ( int ) value );
		
		return this;
	}
	
	public PacketBuilder putLong( String name, long value )
	{
		validateField( name, DataType.LONG );
		
		values.put( name, value );
		
		return this;
	}
	
	public PacketBuilder putClassicString( String name, String value )
	{
		validateField( name, DataType.CLASSIC_STRING );
		
		if( value.length() > 64 )
		{
			throw new IllegalArgumentException( "String exceeds maximum length of 64 characters" );
		}
		
		values.put( name, value );
		
		return this;
	}
	
	public PacketBuilder putString( String name, String value )
	{
		validateField( name, DataType.STRING );
		
		values.put( name, value );
		
		return this;
	}
	
	public PacketBuilder putByteArray( String name, byte[] value )
	{
		validateField( name, DataType.BYTE_ARRAY );
		
		if( value.length > 1024 )
		{
			throw new IllegalArgumentException( "Byte array exceeds maximum length of 1024 characters" );
		}
		
		values.put( name, value );
		
		return this;
	}
}
